package com.yyt.yytojbackendjudgeservice.judge.strategy;

import cn.hutool.json.JSONUtil;
import com.yyt.yytojbackendmodel.model.codesandbox.JudgeInfo;
import com.yyt.yytojbackendmodel.model.dto.question.JudgeCase;
import com.yyt.yytojbackendmodel.model.dto.question.JudgeConfig;
import com.yyt.yytojbackendmodel.model.entity.Question;
import com.yyt.yytojbackendmodel.model.enums.JudgeInfoMessageEnum;


import java.util.List;

/**
 * 默认的判题逻辑
 */
public class DefaultJudgeStratege implements JudgeStratege{
    /**
     * 执行判题
     * @param judgeContext
     * @return
     */
    @Override
    public JudgeInfo doJudge(JudgeContext judgeContext) {
        List<String> inputList = judgeContext.getInputList();
        List<String> outputList = judgeContext.getOutputList();
        JudgeInfo judgeInfo = judgeContext.getJudgeInfo();
        Question question = judgeContext.getQuestion();
        String judgeCase = question.getJudgeCase();
        List<JudgeCase> judgeCaseList = JSONUtil.toList(judgeCase, JudgeCase.class);
        JudgeInfoMessageEnum judgeInfoMessageEnum = JudgeInfoMessageEnum.ACCPETED;

        long memory = judgeInfo.getMemory();
        long time = judgeInfo.getTime();

        //生成返回的JudgeInfo
        JudgeInfo judgeInfoResponce=new JudgeInfo();
        judgeInfoResponce.setMemory(memory);
        judgeInfoResponce.setTime(time);
        judgeInfoResponce.setMessage(judgeInfoMessageEnum.getValue());

        //输出用例和预期输出用例的个数是否相等
        if(outputList.size()!=inputList.size()){
            judgeInfoMessageEnum=JudgeInfoMessageEnum.WRONG_ANSWER;
            judgeInfoResponce.setMessage(judgeInfoMessageEnum.getValue());
            return judgeInfoResponce;
        }
        //依次判断每一项输出和预期输出是否相等
        for(int i=0;i<outputList.size();i++){
            if(!outputList.get(i).equals(judgeCaseList.get(i).getOutput())){
                judgeInfoMessageEnum=JudgeInfoMessageEnum.WRONG_ANSWER;
                judgeInfoResponce.setMessage(judgeInfoMessageEnum.getValue());
                return judgeInfoResponce;
            }
        }
        //判断限制是否符合——时间、空间
        String judgeConfigStr = question.getJudgeConfig();
        JudgeConfig judgeConfig = JSONUtil.toBean(judgeConfigStr, JudgeConfig.class);
        long memoryLimit = judgeConfig.getMemoryLimit();
        long timeLimit = judgeConfig.getTimeLimit();
        //——内存超过
        if(memory>memoryLimit){
            judgeInfoMessageEnum=JudgeInfoMessageEnum.MEMORY_LIMIT_EXCEEDED;
            judgeInfoResponce.setMessage(judgeInfoMessageEnum.getValue());
            return judgeInfoResponce;
        }
        //——时间超过
        if(time>timeLimit){
            judgeInfoMessageEnum=JudgeInfoMessageEnum.TIME_LIMIT_EXCEEDED;
            judgeInfoResponce.setMessage(judgeInfoMessageEnum.getValue());
            return judgeInfoResponce;
        }
        return judgeInfoResponce;
    }
}
